﻿using Simulation.Framework;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;

namespace Easy.Game2d
{
    public class MonsterItem : MonoBehaviour
    {
        #region data
        public float _speed = 2;
        public int _hp = 1;
        private Transform _player;
        private UnityAction _unityAction;
        #endregion

        #region logic - Monster move
        public void StartCor(Transform player,int hp, UnityAction unityAction)
        {
            _hp = hp;
            _player =player;
            _unityAction = unityAction;
            StartCoroutine(WaitPlayerMove());
        }
        private IEnumerator WaitPlayerMove()
        {
            while (true)
            {
                MonsterMove();
                yield return new WaitForFixedUpdate();
            }
        }
        private void MonsterMove()
        {
            this.transform.position = Vector3.MoveTowards(transform.position, _player.position, _speed * Time.fixedDeltaTime);
            //this.transform.Translate((_player.position - this.transform.position) * _speed * Time.fixedDeltaTime);
        }
        #endregion

        #region trigger

        private void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.CompareTag("bullet"))
            {
                _hp=_hp- collision.GetComponent<BulletItem>().damage;
                if (_hp <= 0)
                {
                    _unityAction?.Invoke();
                    StartCoroutine(WaitDes());
                    EventUtil.DispatchEvent(EventData.AddValueClick, 10);
                }
            }
        }
        public void MonsterHide()
        {
            _unityAction?.Invoke();
            StartCoroutine(WaitDes());
            EventUtil.DispatchEvent(EventData.AddValueClick, 10);
        }
        private IEnumerator WaitDes()
        {
            this.transform.localScale = new Vector3(0, 0, 0);
            yield return new WaitForSeconds(2);
            Destroy(this.gameObject);
        }
        #endregion

    }
}
